package com.mreko.dashupload;

import android.widget.ProgressBar;
import android.widget.TextView;

public class DashServer {

	private volatile static DashServer instance = null;
	private ServerCommunicateUtil serverCommunicateUtil;

	private DashServer() {
		this.serverCommunicateUtil = new ServerCommunicateUtil();
	}

	public static DashServer getInstance() {
		// 先检查实例是否存在，如果不存在才进入下面的同步块
		if (instance == null) {
			// 同步块，线程安全的创建实例
			synchronized (DashServer.class) {
				// 再次检查实例是否存在，如果不存在才真正的创建实例
				if (instance == null) {
					instance = new DashServer();
				}
			}
		}
		return instance;
	}

	public int uploadFile(String title,
			int segmentTotal, String[] srcPaths,TextView textView,
			ProgressBar progressBar) {
		//first query server whether the video status to found it is a new upload
		//or it is a resume upload or it is already uploaded
		int status=serverCommunicateUtil.getVideostatus( title, segmentTotal);
		switch(status){
		case DashMessage.UPLOAD_NOTFOUND:
			//upload new file
			new UploadTask(textView, progressBar).execute(srcPaths);
			break;
		case DashMessage.UPLOAD_FINISHED:
			//already exist do nothing
			break;
		default:
			//resume upload file status is how many segements server received
			//construct String array that the first one is how many uploaded
			String[] newSrcPath=new String[srcPaths.length+1];
			newSrcPath[0]=segmentTotal-status+"";
			for(int i=1;i<=srcPaths.length;i++){
				newSrcPath[i]=srcPaths[i-1];
			}
			new ResumeUploadTask(textView, progressBar).execute(newSrcPath);
            break;
	   }
		return status;
	}
}
